package com.jacen.fzxs.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jacen.fzxs.entity.UserEntity;
import com.jacen.fzxs.service.IRoleRightService;
import com.jacen.fzxs.service.IUserService;
import com.jacen.fzxs.util.DateUtils;
import com.jacen.fzxs.util.MD5;
import com.jacen.fzxs.util.StrUtils;
import com.jacen.fzxs.util.Utils;

/**
 * 登录Controller
 * @author Jacen
 *
 */
@Controller
public class LoginController extends BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	public static String USERNAME = "username_attr";
	public static String RIGHT_MARK_SET = "right_mark_set";
	@Resource
	private IUserService userService;
	@Resource
	private IRoleRightService roleRightService;
	
	/**
	 * 进入登录界面
	 * @param session
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/login.do",method = RequestMethod.GET)
	public String login(HttpSession session,String username,ModelMap modelMap,Integer error,String url){
		if(error==null)error =-1;
		if(url==null)url ="none";
		modelMap.addAttribute("error", error);
		modelMap.addAttribute("url", url);
		if(session.getAttribute(USERNAME) != null) return "redirect:/index.do";
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss") +"->进入系统登陆界面...");
    return "login2";
	}
	
	/**
	 * 登录
	 * @param session
	 * @param username
	 * @param password
	 * @param vericode
	 * @return
	 */
	@RequestMapping(value = "/login.do",method = RequestMethod.POST)
	@ResponseBody
	public String postLogin(HttpSession session,String username, String password, String vericode){
		UserEntity userEntity = null;
		try{
			if(StrUtils.isEmpty(username)) return Utils.errorJsonResp("账号不能为空");
	    if(StrUtils.isEmpty(password)) return Utils.errorJsonResp("密码不能为空");
	    password = MD5.MD5Encode(password);
	    userEntity = userService.login(username, password);
	    if(userEntity==null) return Utils.errorJsonResp("用户名或者密码不正确");
	    session.setAttribute(USERNAME, userEntity);
		}catch(Exception e){
			return Utils.errorJsonResp(e.getMessage());
		}
	    //获取该用户角色的所有权限
	    try{
	    	roleRightService.getUserRight(session,userEntity);
	    }catch(Exception e){
	    	return Utils.errorJsonResp(e.getMessage());
	    }
	    logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+username + "登陆系统");
		return Utils.normalJsonResp();
	}
	
	/**
	 * 主页面
	 * @param session
	 * @return
	 */
	@RequestMapping("/index.do")
	public String index(HttpSession session){
		return "index";
	}
	
	/**
	 * 欢迎页面
	 * @param session
	 * @return
	 */
	@RequestMapping("/home.do")
	public String home(HttpSession session){
		return "home";
	}
	
	/**
	 * 进入更新密码界面
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/updatePwd.do", method = RequestMethod.GET)
	public String updatePwd(HttpServletRequest request,ModelMap modelMap){
		UserEntity userEntity = getLocalUser(request);
		modelMap.put("user", userEntity);
		return "user/updatePwd";
	}
	
	/**
	 * 更新密码
	 * @param request
	 * @param session
	 * @param username
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updatePwd.do", method = RequestMethod.POST)
	@ResponseBody
	public String updatePwdPost(HttpServletRequest request,HttpSession session, String username,String oldPwd,String newPwd) throws Exception{
		if(StrUtils.isEmpty(username)) return Utils.errorJsonResp("账号不能为空");
    if(StrUtils.isEmpty(oldPwd)) return Utils.errorJsonResp("旧密码不能为空");
    if(StrUtils.isEmpty(newPwd)) return Utils.errorJsonResp("新密码不能为空");
		
		UserEntity userEntity = getLocalUser(request);
		if(!oldPwd.equals(userEntity.getPassword())){
			return Utils.errorJsonResp("旧密码错误");
		}
		userEntity.setPassword(newPwd);
		userService.update(userEntity);
		clearLocalUser();
    session.invalidate();
    logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+username + "修改密码成功");
		return Utils.normalJsonResp("密码修改成功，请重新登陆");
	}
	
	/**
	 * 退出
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout.do")
    public String logout(HttpServletRequest request) {
    	HttpSession session = request.getSession(false);
    	UserEntity userEntity = null;
    	if(session != null) {
    		userEntity = getLocalUser(request);
    		clearLocalUser();
        session.invalidate();
    	}
    	if(userEntity!=null)
    		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户："+userEntity.getUserName() + "登出系统成功");
        return "redirect:login.do";
    }

}
